package com.lu.service;


import com.alibaba.fastjson.JSONObject;
import com.lu.mapper.MessagesMapper;
import com.lu.pojo.Messages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/websocket/{guid}")
public class WebSocket {
    private Session session;
    private String guid;
    private static Map<String, WebSocket> webSockets = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(@PathParam("guid") String guid, Session session) {
        this.session = session;
        this.guid = guid;
        webSockets.put(guid, this);
        System.out.println(guid);
        System.out.println(session);
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this.guid);
    }

    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    @OnMessage
    public void onMessage(String message) {

        System.out.println("收到客户端发来的消息" + message);

        Messages object = JSONObject.parseObject(message, Messages.class);
        object.setMtime(new Date());
        System.out.println(webSockets.get(this.guid));
        System.out.println(object);
//        getMessageService(messageService,object);
        send(JSONObject.toJSONString(object), String.valueOf(object.getMtouserid()));
    }

    public void send(String message){
        webSockets.forEach((key, value) -> {
            try {
                value.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    public void send(String message, String guid){
        webSockets.forEach((key, value) -> {
            try {
                if (key.equals(guid)) {
                    value.session.getBasicRemote().sendText(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

//    @Resource
//    public void getMessageService(MessageServiceImpl messageService,Messages messages){
//        WebSocket.messageService = messageService;
//        send(messageService.getMessages(messages.getMfromuserid(),messages.getMtouserid()).toString());
//    }

}